package com.core.controller;


import com.common.constants.CaptchaConstant;
import com.common.enums.ErrorCode;
import com.common.model.dto.user.UserLoginDTO;
import com.common.model.vo.SysUserVO;
import com.common.response.BaseResponse;
import com.common.response.ResultUtils;
import com.core.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class LoginController {

    @Resource
    private SysUserService sysUserService;
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResponse<SysUserVO> userLoginWithPost(
            @RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request) {

        /** 先对验证码进行验证 */
        try {
            String random =
                    (String) request.getSession().getAttribute(CaptchaConstant.CAPTCHA_KEY);
            if (StringUtils.isBlank(userLoginDTO.getCaptcha().trim())) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请输入验证码");
            }
            if (!random.equalsIgnoreCase(userLoginDTO.getCaptcha().trim())) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "验证码错误，请重新输入");
            }
        } catch (Exception e) {
            log.error("验证码校验失败", e);
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "验证码校验失败，可能的原因（1.验证码过期，请重新获取 2.验证码错误，请重新输入）");
        }

        /** 验证码验证通过，开始验证登录账号和密码 */
        String userName = userLoginDTO.getUserName().trim();
        String userPassword = userLoginDTO.getUserPassword().trim();
        Integer isRememberMe = userLoginDTO.getIsRememberMe();

        // 账号和密码的参数校验
        if (StringUtils.isAnyBlank(userName, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "登录账号或密码不能为空");
        }
        // 执行登录的业务Service
        SysUserVO sysUserVO = sysUserService.userLogin(userName, userPassword,isRememberMe, request);
        // 验证码 + 账号 + 密码 都验证成功 则返回 jwt 令牌
        return ResultUtils.success(sysUserVO);
    }
}
